<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <canvas id="line" width="500" height="500"></canvas>
  <script>
    // 固定用法
    const canvas = document.querySelector('#line')
    const ctx = canvas.getContext('2d')

    // ctx.beginPath()
    // ctx.moveTo(100, 100)
    // ctx.lineTo(400, 100)
    // ctx.strokeStyle = 'purple'
    // ctx.lineWidth = 10
    // ctx.stroke()
    // ctx.closePath()

    drawline(100, 100, 400, 100, '#f40', 5)
    drawline(400, 100, 400, 400, '#4ff', 5)
    drawline(400, 400, 100, 400, '#0f4', 5)
    drawline(100, 400, 100, 100, '#ff6', 5)
    // 封装画直线函数
    function drawline(x1, y1, x2, y2, color, width) {
      ctx.beginPath()
      ctx.moveTo(x1, y1)
      ctx.lineTo(x2, y2)
      ctx.strokeStyle = color
      ctx.lineWidth = width
      ctx.stroke()
      ctx.closePath()
    }
  </script>
</body>

</html>